package cn.kgc.tangcco.utils.mybatis;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

/**
 * @author 李昊哲
 * @version 1.0
 * @date 2020/6/18 上午9:58
 */
public abstract class MyBatisUtil {
    private static ThreadLocal<SqlSession> t = new ThreadLocal<>();
    // 声明核心配置文件路径
    private static String resource = "mybatis/mybatis-config.xml";
    // 加载核心配置文件到字符流中
    private static Reader reader;
    // 构建会话工场即获取数据源
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            reader = Resources.getResourceAsReader(resource);
            // 构建会话工场即获取数据源
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSession() {
        SqlSession sqlSession = t.get();
        if (sqlSession == null) {
            sqlSession = sqlSessionFactory.openSession();
            t.set(sqlSession);
        }
        // 从数据源获取连接
        return sqlSession;
    }
    public static void close(){
        SqlSession sqlSession = getSession();
        sqlSession.close();
        t.remove();
    }
    public static void commitAndClose(){
        SqlSession sqlSession = getSession();
        sqlSession.commit();
        sqlSession.close();
        t.remove();
    }
    public static void rollbackAndClose(){
        SqlSession sqlSession = getSession();
        sqlSession.rollback();
        sqlSession.close();
        t.remove();
    }
}
